package com.weiadmin.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域设置
 * @author: shizhongyu
 * @date: 2023年03月18日 17:08
 */
@Configuration
public class CorsConfig {
    @Value("${cors.enabled}")
    private boolean corsEnabled;

    @Value("${cors.allow-origin}")
    private String corsAllowOrigin;

    @Value("${cors.allow-methods}")
    private String corsAllowMethods;

    @Value("${cors.allow-headers}")
    private String corsAllowHeaders;

    @Bean
    public CorsFilter corsFilter() {
        if(!corsEnabled) {
            return null; // 如果没有开启跨域，返回null
        }
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin(corsAllowOrigin);
        config.addAllowedHeader(corsAllowHeaders);
        config.addAllowedMethod(corsAllowMethods);
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
